package com.newthread.android.client;

import android.content.Context;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import com.newthread.android.bean.remoteBean.bbs.Post;
import com.newthread.android.bean.remoteBean.bbs.PostType;
import com.newthread.android.manager.iMangerService.IRemoteService;
import com.newthread.android.util.Loger;
import com.newthread.android.util.TimeUtil;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by jindongping on 15/5/29.
 */
public class PostClient implements IRemoteService<Post> {
    private Context context;

    public PostClient(Context context) {
        this.context = context;
    }

    @Override
    public void add(Post post, SaveListener saveListener) {
        if (post.getAuthor() == null) {
            Loger.V("作者为空");
            return;
        }
        if (post.getTitle() == null || post.getTitle().equals("")) {
            Loger.V("主题为空");
            return;
        }
        if (post.getType() == null) {
            PostType type = new PostType();
            //默认类型
            type.setObjectId("65bfa90e13");
            post.setType(type);
        }
        post.save(context, saveListener);
    }

    @Override
    public void update(Post post, UpdateListener updateListener) {
        if (post.getAuthor() == null) {
            Loger.V("作者为空");
            return;
        }
        if (post.getTitle() == null || post.getTitle().equals("")) {
            Loger.V("主题为空");
            return;
        }
        post.update(context, updateListener);
    }

    /**
     * 根据作者和时间查询指定帖子
     *
     * @param post
     * @param findListener
     */
    @Override
    public void querry(Post post, FindListener<Post> findListener) {
        if (post.getAuthor() == null) {
            Loger.V("作者为空");
            return;
        }
        if (post.getCreatedAt() == null || post.getCreatedAt().equals("")) {
            Loger.V("时间为空");
            return;
        }
        BmobQuery<Post> query = new BmobQuery<Post>();
        query.addWhereEqualTo("author", new BmobPointer(post.getAuthor()));
        Calendar cal = Calendar.getInstance();
        cal.setTime(TimeUtil.toDate(post.getCreatedAt()));
        long mills =cal.getTimeInMillis()-10;
        cal.setTimeInMillis(mills);
        Date date =cal.getTime();
        //查询0.01秒前发送 基本上只有一个了
        query.addWhereGreaterThan("createdAt", new BmobDate(date));
        query.findObjects(context, findListener);
    }

    @Override
    public void delete(Post post, final DeleteListener deleteListener) {
        post.delete(context, post.getObjectId(), deleteListener);
    }
}
